package com.wlyy.bcwlw.common.utils;

import java.io.StringWriter;
import java.util.Iterator;
import java.util.Map;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

/**
 * 
 * @ClassName. TemplateUtil
 * @Description. 模版工具类
 * @author zhangyang
 * @date 2015年8月31日 下午3:15:10
 * @version V1.0
 */
public class TemplateUtil {

	public static String velocity(String templateStr, Map<?, ?> map) {
		// 初始化并取得Velocity引擎
		VelocityEngine ve = new VelocityEngine();
		ve.init();
		// 取得velocity的上下文context
		VelocityContext context = new VelocityContext();
		// 把数据填入上下文
		Iterator<?> entries = map.entrySet().iterator();
		while (entries.hasNext()) {
			@SuppressWarnings("rawtypes")
			Map.Entry entry = (Map.Entry) entries.next();
			context.put(String.valueOf(entry.getKey()), entry.getValue());
		}
		// 输出流
		StringWriter writer = new StringWriter();
		// 转换输出
		ve.evaluate(context, writer, "", templateStr); // 关键方法
		return writer.toString();

	}
	
	public static String velocityJSON(String templateStr, String json) {
		return velocity(templateStr,JSON.parseObject(json, new TypeReference<Map<String, String>>() {}));
	}
	 
}
